package com.example.demo.netty.heartbeat.client;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.IOException;
import java.util.concurrent.*;

import java.util.Random;

public class NettyClient {
    private  static Bootstrap bootstrap;
    public static void main(String[] args) {

        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(10);
        try {
            bootstrap = new Bootstrap();

            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new StringEncoder())
                                    .addLast(new StringDecoder())
                                    .addLast(new ClientHandler());
                        }
                    });
            // 断线重连
            connect();
            // 阻塞一下只是为了看断线重连的结果
            try {
                System.in.read();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            // 不用阻塞了,前面已经阻塞过了
//            connect.channel().closeFuture().sync();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }

    }

    public static  void connect(){
        try {
            ChannelFuture connect = bootstrap.connect("127.0.0.1", 7000).sync();

            connect.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()){
                        System.out.println("连接成功！");
                    }else{
                        System.out.println("连接中");
                        Thread.sleep(3000);
                        connect();

                    }
                }
            });
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
